package com.randi.file.service;

import com.randi.common.enums.ResultCode;
import com.randi.common.exception.ServiceException;
import com.randi.common.utils.RedisUtil;
import com.randi.file.entity.SysFile;
import com.randi.file.entity.vo.FileSliceMergeVo;
import com.randi.file.enums.FileSliceMergeStatusEnum;
import com.randi.file.utils.UploadSliceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author ziye
 */
@Component
public class ThreadFileService {

    private static final Logger logger = LoggerFactory.getLogger("com.randi.file.service.ThreadFileService");

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ISysFileService sysFileService;

    private void printLog(FileSliceMergeStatusEnum status, String taskId) {
        logger.info("------------------------------- 多线程任务 -------------------------------");
        logger.info("任务名称：{}", "分片合并");
        logger.info("任务编号：{}", taskId);
        logger.info("任务状态：{}", status);
        logger.info("------------------------------------------------------------------------");
    }

    /**
     * 创建文件信息
     *
     * @param sliceMerge FileSliceMergeVo
     * @return SysFile
     */
    private SysFile createSysFile(FileSliceMergeVo sliceMerge) {
        SysFile sysFile = new SysFile();
        sysFile.setFileHash(sliceMerge.getFileHash());
        sysFile.setFileName(sliceMerge.getFileName());
        sysFile.setFileSuffix(sliceMerge.getFileSuffix());
        sysFile.setFileSize(sliceMerge.getFileSize());
        sysFile.setMineType(sliceMerge.getMineType());
        return sysFile;
    }

    /**
     * 处理分片合并任务
     *
     * @param sliceMerge FileSliceMergeVo
     */
    @Async("TaskExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void handleSliceMergeTask(String taskId, FileSliceMergeVo sliceMerge) {
        // 初始化状态
        redisUtil.setCache(taskId, FileSliceMergeStatusEnum.AWAIT);
        printLog(FileSliceMergeStatusEnum.AWAIT, taskId);
        FileSliceMergeStatusEnum statusEnum = FileSliceMergeStatusEnum.FAIL;
        try {
            sysFileService.insertSysFile(createSysFile(sliceMerge));
            boolean status = UploadSliceUtils.sliceMerge(sliceMerge);
            if (status) {
                statusEnum = FileSliceMergeStatusEnum.SUCCESS;
            }
        } finally {
            redisUtil.setCache(taskId, statusEnum, 5, TimeUnit.MINUTES);
            printLog(statusEnum, taskId);
        }

    }
}
